defmodule SockWorkstation.PythonRunnerGen do
  use GenServer

  @python_path  "/mnt/z/py-envs/xiaozhi/bin/python"
  @script_path  "/home/thy/sock_workstation/python/watch_and_run.py"
  # @timeout 10000


  # 客户端接口
  def start_link(_opts) do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def run_script do
    GenServer.cast(__MODULE__, :run_script)
  end

  # 服务器实现
  @impl true
  def init(_opts) do
    IO.puts("PythonRunner started")
    # 在启动时运行 Python 脚本
    # run_script()
    port = Port.open({:spawn, "#{@python_path} #{@script_path}"}, [:binary, :exit_status])
    # receive do
    #   {^port, {:data, data}} ->
    #     IO.puts("Received from Python: #{data}")
    #   {^port, {:exit_status, status}} ->
    #     IO.puts("Python script exited with status #{status}")
    # after
    #   @timeout ->
    #     IO.puts("Timeout: No response from Python script within #{@timeout}ms")
    #     Port.close(port)  # 关闭端口
    # end
    {:ok, %{port: port}}
  end
  @impl true
  def terminate(_reason, %{port: port}) do
    # 向 Python 脚本发送终止信号
    Port.command(port, "exit\n")
    # 关闭端口
    Port.close(port)
    :ok
  end
end

  # @impl true
  # def handle_cast(:run_script, state) do
  #   run_python_script()
  #   {:noreply, state}
  # end

  # defp run_python_script do
    # 定义 Python 脚本路径和环境
    # python_path = "/mnt/z/py-envs/xiaozhi/bin/python"
    # script_path = "/home/thy/sock_workstation/python/watch_and_run.py"

    # 使用 System.cmd 启动 Python 脚本
    # System.cmd(python_path, [script_path])

    # 打印输出和状态
    # IO.puts("Python script output:")
    # IO.puts(output)
    # IO.puts("Exit status: #{status}")
  # end
# end
